package com.xuecheng.content.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import io.minio.DeleteObjectTagsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.messages.DeleteObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioTemplate {

    // 声明MIME类型常量
    public static final String TEXT_HTML = "text/html";
    public static final String IMAGE_JPG = "image/jpg";

    @Autowired
    private MinioProperties minioProperties;

    private MinioClient minioClient;

    //初始化minioClient
    @PostConstruct
    public void init(){
        minioClient=MinioClient.builder()
                .credentials(minioProperties.getAccessKey(),minioProperties.getSecretKey())
                .endpoint(minioProperties.getEndpoint())
                .build();
    }

    //文件上传
    public String upload(InputStream inputStream,String fileName){
        try {
            //上传的文件名
            String filePath="images/"+ DateTime.now().toString("yyyy/MM/dd/")+ UUID.randomUUID().toString()
                    +"."+ FileUtil.extName(fileName);
            //上传参数
            PutObjectArgs args=PutObjectArgs.builder()
                    .bucket(minioProperties.getBucket())//桶名
                    .contentType(IMAGE_JPG)//MIME类型
                    .object(filePath)//文件路径
                    .stream(inputStream, inputStream.available(), -1)//使用输入流
                    .build();
            //上传
            minioClient.putObject(args);
            //访问地址
            String imageUrl=minioProperties.getDomain()+"/"+minioProperties.getBucket()+"/"+filePath;
            //返回地址
            return imageUrl;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    //文件删除
    public void deleteObject(String fileUrl){
        try {
            int indexOfBucket = fileUrl.indexOf("images/");
            String objectName = fileUrl.substring(indexOfBucket);
            RemoveObjectArgs args=RemoveObjectArgs.builder()
                    .object(objectName)
                    .bucket(minioProperties.getBucket())
                    .build();
            minioClient.removeObject(args);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    //Html删除
    public void deleteHtml(String courseId){
        try {
            String objectName="pages/"+courseId+".html";
            RemoveObjectArgs args=RemoveObjectArgs.builder()
                    .object(objectName)
                    .bucket(minioProperties.getBucket())
                    .build();
            minioClient.removeObject(args);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    // 抽取文件上传方法（html页面资源）
    public String uploadHtml(InputStream inputStream, String filename) { // as123123abc.jpg
        try {
            // 配置上传的请求地址  /pages/47.html
            String filePath = "pages/"+filename;

            // 完成文件上传
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath) // 文件名
                    .contentType(TEXT_HTML) // 文件类型
                    .bucket(minioProperties.getBucket()) // 桶名
                    .stream(inputStream, inputStream.available(), -1)  //参数1:文件流  参数2:文件大小  参数3: 分片大小
                    .build();
            minioClient.putObject(putObjectArgs);

            // 返回文件名
            String urlPath = minioProperties.getDomain() + "/" + minioProperties.getBucket() + filePath;

            return urlPath;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
